/*  basic function  */
import CONST from './constant'
import API from './api'
import gcoord from 'gcoord'

export default function () {
  let Const = CONST()
  let Api = API()

  let o = {
    // 获取文档宽度
    getDocumentWidth () {
      return document.documentElement.clientWidth || document.body.clientWidth
    },

    // 获取文档高度
    getDocumentHeight () {
      return document.documentElement.clientHeight || document.body.clientHeight
    },

    // 获取常量(type为常量类型, name为常量名称)
    getConst (type, name) {
      if (Const[type] && Const[type][name]) {
        return Const[type][name]
      } else {
        console.log('常量不存在')
        return false
      }
    },

    // 获取常量对应的名字
    getNameByConst (type, name, value) {
      if (Const[type] && Const[type][name]) {
        let t = Const[type][name].filter(function (val) {
          return val.value === value
        })
        if (t && t.length) {
          return t[0].name
        } else {
          return false
        }
      } else {
        console.log('常量不存在')
        return false
      }
    },

    // localStorage封装,默认过期时间为1天
    setLocalStorage (key, value) {
      var curtime = new Date().getTime() // 获取当前时间 ，转换成JSON字符串序列
      var valueDate = JSON.stringify({
        val: value,
        timer: curtime
      })
      try {
        localStorage.setItem(key, valueDate)
        return valueDate
      } catch (e) {
        // 兼容性写法
        console.log(e)
      }
    },

    getLocalStorage (key) {
      var exp = 1000 * 60 * 60 * 24 // 一天的毫秒数
      if (localStorage.getItem(key)) {
        var vals = localStorage.getItem(key) // 获取本地存储的值
        var dataObj = JSON.parse(vals) // 将字符串转换成JSON对象
        // 如果(当前时间 - 存储的元素在创建时候设置的时间) > 过期时间
        var isTimed = new Date().getTime() - dataObj.timer > exp
        if (isTimed) {
          console.log('存储已过期')
          localStorage.removeItem(key)
          return null
        } else {
          var newValue = dataObj.val
        }
        return newValue
      } else {
        return null
      }
    },
    // sessionStorage封装
    setSessionStorage (key, data) {
      let storage = window.sessionStorage
      let myData = data
      if (typeof myData === 'object' || typeof myData === 'function') {
        storage.setItem(key, JSON.stringify(myData))
      } else {
        storage.setItem(key, myData)
      }
      return myData
    },

    getSessionStorage (key) {
      let storage = window.sessionStorage
      return storage.getItem(key)
    },

    // 接口地址封装
    getUrl (key, id) {
      let url = Api.getUrl(key, id)
      if (url.indexOf('batterycar') > -1) {
        url = url.replace('standard', 'batterycar')
      }
      return url
    },

    // 公用弹窗
    popup (params) {
      let html = ''
      let _this = this
      let $popup = {}
      let pWidth = params.w ? params.w + 'px' : 'auto'

      let pHeight = params.h ? params.h + 'px' : 'auto'
      if (!$('.app-popup').length) {
        html +=
          '<div class="app-popup" style="width:' +
          pWidth +
          ';height:' +
          pHeight +
          '">'
        html += '<div class="app-popup-close"></div>'
        html += '<div class="app-popup-content"></div>'
        html += '</div>'
        $('body').append(html)
        $popup = $('.app-popup')
        $('.app-popup-content').html(params.content)
        $popup.show()
        this.shadow(function () {
          $popup.find('.app-popup-content').empty()
        })
      } else {
        $popup = $('.app-popup')
        $popup.width(pWidth).height(pHeight)
        $('.app-popup-content').html(params.content)
        $popup.show()
        this.shadow(function () {
          $popup.find('.app-popup-content').empty()
        })
      }

      $('.app-popup-close').on('click', function () {
        $popup.hide()
        $popup.find('.app-popup-content').empty()
        _this.hideShadow()
      })
    },

    // 公用半透明阴影
    shadow (func) {
      let _this = this
      let $shadow = $('.app-shadow')
      if (!$shadow.length) {
        let html = ''
        html += '<div class="app-shadow"></div>'
        $('body').append(html)
        $shadow = $('.app-shadow')
        $shadow.show()

        $shadow.on('click', function () {
          $('.app-popup').hide()
          _this.hideShadow()
          if (func) {
            func()
          }
        })
      }
    },

    hideShadow () {
      $('.app-shadow').remove()
    },

    // 计算当前时间的时间差
    timeConvert (timeValue) {
      let date1 = timeValue // 开始时间
      let date2 = new Date() // 结束时间
      let date3 = date2.getTime() - new Date(date1).getTime() // 时间差的毫秒数
      // 计算出相差天数
      let days = Math.floor(date3 / (24 * 3600 * 1000))
      // 计算出小时数
      let leave1 = date3 % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
      let hours = Math.floor(leave1 / (3600 * 1000))
      // 计算相差分钟数
      let leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
      let minutes = Math.floor(leave2 / (60 * 1000))
      // 计算相差秒数
      let leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
      let seconds = Math.round(leave3 / 1000)
      let showTime = ''
      if (days >= 0) {
        showTime = days + '天 ' + hours + '小时' + minutes + '分'
      } else if (days < 0 || hours < 0 || minutes < 0 || seconds < 0) {
        showTime = '-'
      }
      return showTime
    },

    // 个位数转化为'0x'形式
    singleAddZero (num) {
      return num < 10 ? '0' + num : num
    },

    // date转化为string(yyyy-MM-dd hh-mm-ss)
    dateToString (newDate) {
      let tDate = newDate
      if (!tDate) {
        tDate = new Date()
      }
      let yyyy = tDate.getFullYear()

      let MM = this.singleAddZero(tDate.getMonth() + 1)

      let dd = this.singleAddZero(tDate.getDate())

      let hh = this.singleAddZero(tDate.getHours())

      let mm = this.singleAddZero(tDate.getMinutes())

      let ss = this.singleAddZero(tDate.getSeconds())
      return yyyy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss
    },

    // 生成随机字符串
    randomString (len) {
      len = len || 32
      const $chars =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789'
      const maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },

    // 地图坐标转换
    transCoordinate (lng, lat, type, newType) {
      type = type || 0
      newType = newType || 0
      const obj = {
        0: gcoord.AMap, // GCJ-02
        1: gcoord.BMap, // BD-09
        2: gcoord.WGS84, // WGS84
        3: gcoord.WebMercator // Web Mercator投影，墨卡托投影
      }
      let old = [lng, lat]
      return gcoord.transform(old, obj[type], obj[newType])
    },

    // 判断对象是否为空对象
    isEmptyObject (obj) {
      for (var key in obj) {
        return false
      }
      return true
    },

    // 获取人员进入小区方式（目前应用在【荣振馨苑】小区）
    getEnterType (key, type) {
      console.log(Const, 123)
      return Const[key][type] || ''
    }
  }

  return o
}
